package cn.hloger.spider.demo.jwtDemo;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;

/**
 * 代理接口处理类
 *
 * @author huanglong
 * @version 1.0
 * @date 2024/2/27
 */
//@Component
public class JwtDemo {
    public static void main(String[] args) {
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MTk1NjI2NjYsInVzZXJuYW1lIjoiYWRtaW4ifQ.XWsmOq_eiBHXyc4k71noP2yXQ3M-yjcnGzKM49-y3a8";
        DecodedJWT jwt = JWT.decode(token);
        String username = jwt.getClaim("username").asString();
        System.out.println(username);

        // 校验结果
//        boolean check = JwtUtils.verify(token, username);
        // 根据密码生成JWT效验器
        Algorithm algorithm = Algorithm.HMAC256(encryptSecret(username));
        JWTVerifier verifier = JWT.require(algorithm)
                .withClaim("username", username)
                .build();
        // 效验TOKEN
        DecodedJWT verify = verifier.verify(token);
    }

    /**
     * 根据用户名和秘钥，生成一个新的秘钥，用于JWT加强一些安全性
     *
     * @param userName
     * @return
     */
    private static String encryptSecret(String userName) {

        // 一个简单的登录规则，用户名+当前月份为加密串，意思每个月会变，要重新登录
        // 可自行修改此规则
        Calendar cl = Calendar.getInstance();
        cl.setTimeInMillis(System.currentTimeMillis());
        StringBuffer sb = new StringBuffer(userName)
                .append("&")
                .append(cl.get(Calendar.MONTH));

        // 获取MD5
        String secret = MD5Util.MD5(sb.toString());

        return MD5Util.MD5(userName + "&" + secret);
    }
}
